<?php

declare(strict_types=1);

$CONFIG = [
    /**
     *  不检查key时，将useKey设为false
     *  key为t时验证密码
     */
    'useKey'       =>   true,
    'key'          =>   '72ab8af56bddab33b269c5964b26620a',

    //设置cookie，调用时可无需参数
    'useCookies'   =>   true,
    'cookies'      =>   'WebMonitor',
];

/**
 * @param createToken 匹配 $CONFIG 中的Key，不匹配则直接退出
 * @param e 口令过期时间，以 minute 分钟为单位
 * @param e 为0表示口令永不过期
 * @return key 生成的目标key
 */



//以下为文件主入口
if (empty($_GET['createToken'])) {

    /**
     * @return ErrorCode 0      没有错误
     * @return ErrorCode 10011  token 格式错误
     * @return ErrorCode 10012  IP地址不匹配
     * @return ErrorCode 10013  token 已过期
     */
    function CheckKey($token = '')
    {
        $config = $GLOBALS['CONFIG'];
        if ($config['useKey'] == false)
            return json_encode([
                'ErrorCode'   =>   0,
            ]);

        $t = $token;
        if (empty($t) && $config['useCookies'])
            $t = $_COOKIE[$config['cookies']];

        $key = base64_decode($t);
        if ((strlen($key) % 2) || (!ctype_xdigit($key)))
            return json_encode([
                'ErrorCode'   =>   10011,
            ]);

        $key = hex2bin($key);
        $key = openssl_decrypt($key, 'DES-ECB', $config['key']);
        $array = json_decode($key, true);

        if (
            $_SERVER['HTTP_HOST'] != $array['host'] ||
            $_SERVER['REMOTE_ADDR'] != $array['addr']
        )
            return json_encode([
                'ErrorCode'   =>   10012,
            ]);

        if (
            $array['expires'] != 0 &&
            (($array['time'] + $array['expires'] * 60) < time())
        )
            return json_encode([
                'ErrorCode'   =>   10013,
            ]);

        return json_encode([
            'ErrorCode'   =>   0,
        ]);
    }

    return;
} elseif ($_GET['createToken'] == $CONFIG['key']) {

    $expires = 0;
    if (!empty($_GET['e']) && is_numeric($_GET['e']))
        $expires = $_GET['e'];

    $data = [
        'time'      =>   time(),
        'host'      =>   $_SERVER['HTTP_HOST'],
        'addr'      =>   $_SERVER['REMOTE_ADDR'],
        'expires'   =>   $expires,
    ];

    $key = openssl_encrypt(json_encode($data), 'DES-ECB', $CONFIG['key']);
    $key = bin2hex($key);
    $key = base64_encode($key);

    if ($CONFIG['useCookies']) {
        if ($expires == 0) {
            setcookie($CONFIG['cookies'], $key);
        } else {
            setcookie($CONFIG['cookies'], $key, $data['time'] + 60 * $expires);
        }
    }

    echo 'SetCookie:';
    echo $CONFIG['useCookies'] ? 'true' : 'false';
    echo '<br/>' . $key;

    die();
}
